package com.rc.saas.tenant.controller.recharge;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.redis.RedisLoader;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.fault.RcElecPileFaultRecord;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.enterprise.EnterpriseSubMemberApplySearch;
import com.rc.saas.tenant.search.fault.RcElecPileFaultRecordSearch;
import com.rc.saas.tenant.search.recharge.RechargeOrderSearch;
import com.rc.saas.tenant.service.recharge.RechargeOrderService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.recharge.ExportRechargeOrderVo;
import com.rc.saas.tenant.vo.recharge.RechargeOrderExportVo;
import com.rc.saas.tenant.vo.recharge.RechargeOrderResultVo;
import com.rc.saas.tenant.vo.recharge.RechargeOrderStatisticsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;


/**
 * @author frog
 * @data 2019/11/19
 */
@Controller
@RequestMapping("/rechargeOrder")
public class RechargeOrderController extends TenantBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisLoader redisLoader;

    @Autowired
    private RechargeOrderService rechargeOrderService;

    @Autowired
    private TenantRoleService tenantRoleService;

    /**
     * 跳转会员充值页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String rechargeOrderPage() {
        return "/templates/recharge/rechargeOrder/rechargeOrder";
    }

    /**
     * 数据权限过滤
     * @param search
     * @return
     */
    protected RechargeOrderSearch dataAuth(RechargeOrderSearch search){

        TenantUser user = getSessionTenantUser();
        TenantRole tenantRole = tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
        if ("3".equals(tenantRole.getRoleType())){
            //企业用户
            search.setEnterpriseId(user.getEnterpriseId());
        }else if ("1".equals(tenantRole.getRoleType())){
            //自定义角色
            if (tenantRole.getDataAuth().endsWith("0")){
                //如果不查询企业会员置0
                search.setEnterpriseId(0L);
            }
        }
        return search;
    }

    /**
     * 返回会员充值列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listRechargeOrder", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo getRechargeOrderList(RechargeOrderSearch rechargeOrderSearch) {
        //数据权限
        dataAuth(rechargeOrderSearch);

        PageInfo<RechargeOrderResultVo> pageInfo = rechargeOrderService.searchByCondition(rechargeOrderSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 跳转农行支付交易详情
     * @return
     */
    @RequestMapping(value = "/detailRechargeOrderIndex",method = RequestMethod.GET)
    public String detailRechargeOrderPage(){
        return "/templates/recharge/rechargeOrder/detailRechargeOrder";
    }

    /**
     * 返回农行支付交易详情
     * @param rechargeOrderSearch
     * @return
     */
    @RequestMapping(value = "/listRechargeOrderDetail",method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listRechargeOrderDetail(RechargeOrderSearch rechargeOrderSearch){
        PageInfo<RechargeOrderResultVo> pageInfo=rechargeOrderService.listPageRechargeOrderDetail(rechargeOrderSearch);
        WebPageInfo webPageInfo=new WebPageInfo(pageInfo.getList(),Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 返回农行支付统计
     * @return
     */
    @RequestMapping(value = "/selectRechargeOrderStatistics",method = RequestMethod.GET)
    @ResponseBody
    public TResponse selectRechargeOrderStatistics(RechargeOrderSearch rechargeOrderSearch){
        RechargeOrderStatisticsVo rechargeOrderStatisticsVo=rechargeOrderService.selectRechargeOrderStatistics(rechargeOrderSearch);
        return TResponse.SUCCESS_DATA(rechargeOrderStatisticsVo);
    }

    /**
     * 导出农行支付详情列表
     * @param rechargeOrderSearch
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/exportRechargeOrderDetail",method = RequestMethod.GET)
    public TResponse exportRechargeOrderDetail(RechargeOrderSearch rechargeOrderSearch, HttpServletResponse response){
        response.setHeader("Set-Cookie", "fileDownload=false; path=/");
        ExportUtils.setDefaultPaging(rechargeOrderSearch);
        if (rechargeOrderSearch.getCount() == 0 || rechargeOrderSearch.getCount() == null) {
            rechargeOrderSearch.setCount(rechargeOrderSearch.getLimit());
        }

        if (rechargeOrderSearch.getCount() > 200000) {
            return TResponse.FAIL("最多导出二十万数据");
        }

        if (rechargeOrderSearch.getCount() >= 100000) {
            String exportData = (String) redisLoader.get("saas:exportData");
            if (exportData != null) {
                return TResponse.FAIL("导出人数过多,请稍后重试");
            }
            TenantUser user = ShiroUtils.getSessionUser();
            redisLoader.set("saas:exportData", user.getTenantCode(), 1000 * 20);
        }

        //导出拼接开始条数
        rechargeOrderSearch.setOffset(rechargeOrderSearch.getLimit() * (rechargeOrderSearch.getOffset() - 1));
        List<RechargeOrderExportVo> list = rechargeOrderService.rechargeOrderExport(rechargeOrderSearch);
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("农行支付详情列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), RechargeOrderExportVo.class).sheet("会员充值信息列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出农行支付详情信息失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


    /**
     * 导出会员充值信息列表
     */
    @ResponseBody
    @RequestMapping("/exportRechargeOrder")
    public TResponse exportRechargeOrder(RechargeOrderSearch rechargeOrderSearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=false; path=/");
        ExportUtils.setDefaultPaging(rechargeOrderSearch);
        if (rechargeOrderSearch.getCount() == 0 || rechargeOrderSearch.getCount() == null) {
            rechargeOrderSearch.setCount(rechargeOrderSearch.getLimit());
        }

        if (rechargeOrderSearch.getCount() > 200000) {
            return TResponse.FAIL("最多导出二十万数据");
        }

        if (rechargeOrderSearch.getCount() >= 100000) {
            String exportData = (String) redisLoader.get("saas:exportData");
            if (exportData != null) {
                return TResponse.FAIL("导出人数过多,请稍后重试");
            }
            TenantUser user = ShiroUtils.getSessionUser();
            redisLoader.set("saas:exportData", user.getTenantCode(), 1000 * 20);
        }

        //数据权限
        dataAuth(rechargeOrderSearch);

        //导出拼接开始条数
        rechargeOrderSearch.setOffset(rechargeOrderSearch.getLimit() * (rechargeOrderSearch.getOffset() - 1));
        List<ExportRechargeOrderVo> list = rechargeOrderService.exportRechargeOrder(rechargeOrderSearch);
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("会员充值信息列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExportRechargeOrderVo.class).sheet("会员充值信息列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出会员充值信息失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }
}
